package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MapperStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 解析 mapper 信息并存储在 configuration 中
 *
 * @author srh
 * @date 2020/02/22
 **/
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream mapperStream) throws DocumentException, ClassNotFoundException {
        Map<String, MapperStatement> map = configuration.getMapperStatementMap();

        Document document = new SAXReader().read(mapperStream);
        Element root = document.getRootElement();
        String namespace = root.attributeValue("namespace");

        // 解析select标签
        parseSelect(map, namespace, root);
        // 解析update标签
        parseUpdate(map, namespace, root);
        // 解析delete标签
        parseDelete(map, namespace, root);
        // 解析insert标签
        parseInsert(map, namespace, root);
    }

    private void parseInsert(Map<String, MapperStatement> map, String namespace, Element root) throws ClassNotFoundException {
        parse(map, namespace, root.selectNodes("insert"));
    }

    private void parseDelete(Map<String, MapperStatement> map, String namespace, Element root) throws ClassNotFoundException {
        parse(map, namespace, root.selectNodes("delete"));
    }

    private void parseUpdate(Map<String, MapperStatement> map, String namespace, Element root) throws ClassNotFoundException {
        parse(map, namespace, root.selectNodes("update"));
    }

    private void parseSelect(Map<String, MapperStatement> map, String namespace, Element root) throws ClassNotFoundException {
        parse(map, namespace, root.selectNodes("select"));
    }

    private void parse(Map<String, MapperStatement> map, String namespace, List<Element> elements) throws ClassNotFoundException {
        for (Element element : elements) {
            String id = element.attributeValue("id");
            String parameterType = element.attributeValue("parameterType");
            String resultType = element.attributeValue("resultType");
            String sql = element.getTextTrim();

            Class<?> paramterClass = getClassType(parameterType);
            Class<?> resultClass = getClassType(resultType);
            MapperStatement mapperStatement = new MapperStatement(id, paramterClass, resultClass, sql);

            String key = String.format("%s.%s", namespace, id);
            if (!map.containsKey(key)) {
                map.put(key, mapperStatement);
            }
        }
    }

    private Class<?> getClassType(String type) throws ClassNotFoundException {
        return Class.forName(type);
    }
}
